//
//  MoyaCacheRequestList.swift
//  Common
//
//  Created by 我骑着蜗牛走天下 on 2025/11/14.
//


import UIKit

class MoyaCacheRequestList: ViewController<MoyaCacheRequestListView> {
    
    let dateListVc = MoyaCacheDateList()
    
    var url: URL?
    
    var dateList: [NetworkCacheItem] = NetworkCacheManager.shared.getCache() {
        didSet{
            contatiner.tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "当前请求"
        
        contatiner.tableView.delegate = self
        contatiner.tableView.dataSource = self
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: contatiner.historyBtn)
        contatiner.historyBtn.addTarget(self, action: #selector(historyBtnClick), for: .touchUpInside)
        
        navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: contatiner.closeBtn),UIBarButtonItem(customView: contatiner.shareBtn)]
        contatiner.closeBtn.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside)
        contatiner.shareBtn.addTarget(self, action: #selector(shareBtnCLick), for: .touchUpInside)
        
        dateListVc.didSelectBlock = { [weak self] tuple in
            guard let self = self else { return }
            
            if let tuple = tuple {
                url = tuple.url
                NetworkCacheManager.shared.loadFileAsync(url: tuple.url, completion: { [weak self] list in
                    guard let self = self else { return }
                    
                    dateList = list
                    
                })
            }else{
                dateList = NetworkCacheManager.shared.getCache()
            }
            
        }
        
        
        
    }
    
    @objc func shareBtnCLick(){
        
        if let url = url {
            // 准备分享内容
            let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: [])
            // 弹出分享面板
            present(activityVC, animated: true, completion: nil)
        }else if let jsonString = dateList.toJSONString() {
            // 准备分享内容
            let activityVC = UIActivityViewController(activityItems: [jsonString] , applicationActivities: [])
            // 弹出分享面板
            present(activityVC, animated: true, completion: nil)
        }
        
    }
    
    
    @objc func historyBtnClick(){
        navigationController?.pushViewController(dateListVc, animated: true)
    }
    
    @objc func closeBtnClick(){
        dismiss(animated: true)
    }
    
}

extension MoyaCacheRequestList: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dateList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.description(), for: indexPath)
        cell.selectionStyle = .none
        
        let item = dateList[indexPath.row]
        
        cell.textLabel?.numberOfLines = 2
        cell.textLabel?.text = dateList[indexPath.row].url
        cell.detailTextLabel?.text = "耗时：\(item.metrics) 报错：\(item.errorDescription) "
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let vc = MoyaCacheRequestDetail()
        vc.item = dateList[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
    }
    
}


class MoyaCacheRequestListView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = .white
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        addSubview(tableView)
        NSLayoutConstraint.activate([
            tableView.topAnchor.constraint(equalTo: self.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            tableView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: self.trailingAnchor)
        ])
        
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var tableView: UITableView = {
        let table = UITableView()
        table.rowHeight = 60
        table.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.description())
        return table
    }()
    
    /// 历史
    lazy var historyBtn: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.blue, for: .normal)
        btn.setTitle("历史", for: .normal)
        return btn
    }()
    
    /// 关闭
    lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.blue, for: .normal)
        btn.setTitle("关闭", for: .normal)
        return btn
    }()
    
    lazy var shareBtn: UIButton = {
        let btn = UIButton()
        btn.setTitleColor(.blue, for: .normal)
        btn.setTitle("分享", for: .normal)
        return btn
    }()
    
}

